package com.etrans.util;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


/**
 * Java Mail 工具类
 * 
 * @author XueQi
 * @version 1.0
 * 
 */
public class MailUtils {
	private static String host;
	private static String username;
	private static String password;
	private static String from;
	private static String nick;

	static {
		try {
			// Test Data
			host = "mail8.foton.com.cn";
			username = "ftappleid@foton.com.cn";
			password = "Foton_20180725";
			from = "ftappleid@foton.com.cn";
			nick = "foton";
			// nick + from 组成邮箱的发件人信息
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private static final  SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * 发送邮件
	 * 
	 * @param to
	 *            收件人列表，以","分割
	 * @param mailSubject
	 *            标题
	 * @param body
	 *            内容
	 * @param filepath
	 *            附件列表,无附件传递null
	 * @return
	 * @throws MessagingException
	 * @throws AddressException
	 * @throws UnsupportedEncodingException
	 */
	public static boolean sendMail(String mailSubject,String toUser,String body,List<String> filepath) {
		System.setProperty("java.net.preferIPv4Stack", "true");
		try {
			String to = toUser;
			if (body == null) {
				body = "";
			}
			if (mailSubject == null) {
				mailSubject = "无主题";
			}
			// 创建Properties对象

			Properties props = System.getProperties();
			// 创建信件服务器
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.auth", "true"); // 通过验证
			// 得到默认的对话对象
			Session session = Session.getDefaultInstance(props, null);
			// 创建一个消息，并初始化该消息的各项元素
			MimeMessage msg = new MimeMessage(session);
			nick = MimeUtility.encodeText(nick);
			msg.setFrom(new InternetAddress(nick + "<" + from + ">"));
			// 创建收件人列表
			if (to != null && to.trim().length() > 0) {
				String[] arr = to.split(",");
				int receiverCount = arr.length;
				if (receiverCount > 0) {
					InternetAddress[] address = new InternetAddress[receiverCount];
					for (int i = 0; i < receiverCount; i++) {
						address[i] = new InternetAddress(arr[i]);
					}
					msg.addRecipients(Message.RecipientType.TO, address);
					msg.setSubject(mailSubject);
					// 后面的BodyPart将加入到此处创建的Multipart中
					Multipart mp = new MimeMultipart();
					// 附件操作
					if (filepath != null && filepath.size() > 0) {
						for (String filename : filepath) {
							MimeBodyPart mbp = new MimeBodyPart();
							// 得到数据源
							FileDataSource fds = new FileDataSource(filename);
							// 得到附件本身并至入BodyPart
							mbp.setDataHandler(new DataHandler(fds));
							// 得到文件名同样至入BodyPart
							mbp.setFileName(fds.getName());
							mp.addBodyPart(mbp);
						}
						MimeBodyPart mbp = new MimeBodyPart();
						mbp.setText(body);
						mp.addBodyPart(mbp);
						// 移走集合中的所有元素
						filepath.clear();
						// Multipart加入到信件
						msg.setContent(mp);
					} else {
						// 设置邮件正文
						msg.setText(body);
					}
					// 设置信件头的发送日期
					msg.setSentDate(new Date());
					msg.saveChanges();
					// 发送信件
					Transport transport = session.getTransport("smtp");
					transport.connect(host, username, password);
					transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
					transport.close();
					return true;
				} else {
					System.out.println("None receiver!");
					return false;
				}
			} else {
				System.out.println("None receiver!");
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public static void main(String[] args) {
		try {
			System.out.println("邮件发送开始====");
			
			sendMail("测试主题", "826234199@qq.com", "试一试", null);

			System.out.println("邮件发送结束====");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	// 参数解释： title：导出excel标题、headers 导出到excel显示的列头、columns 对应数据库字段 、list 导出数据、desc 描述
		@SuppressWarnings({ "deprecation"})
		public static XSSFWorkbook expoortExcelx(String title, String[] columns, String[] headers, List<HashMap<String, Object>> list,String pattern,String desc) throws NoSuchMethodException, Exception {
			// 创建工作薄
			XSSFWorkbook workbook = new XSSFWorkbook();
			// 创建表格
			Sheet sheet = workbook.createSheet(title);
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.length - 1));
			Row titleRow = sheet.createRow(0);
			titleRow.createCell(0).setCellValue(title);
			
			sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, headers.length - 1));
			Row descRow = sheet.createRow(1);
			descRow.createCell(0).setCellValue(desc);
			
			Row headerRow = sheet.createRow(2);
			for (int i = 0; i < headers.length; i++) {
				Cell cell = headerRow.createCell(i);
				XSSFRichTextString text = new XSSFRichTextString(headers[i]);
				cell.setCellValue(text);
			}
			
			// 遍历集合数据，产生数据行
			if (list != null && list.size() > 0) {
				int index = 3;
				for (HashMap<String, Object> dataMap : list) {
					Row row = sheet.createRow(index);
					row.setHeightInPoints(15);
					index++;
					for (short i = 0; i < columns.length; i++) {
						Cell cell = row.createCell(i);
						Object textValue = "";
						try{
							if("response_time".equals(columns[i])){
								String response_time=dataMap.get(columns[i])+"";
								if("null".equals(response_time)){
									textValue="";
								}else if(!StringUtils.isNotEmpty(response_time)){  
									textValue="";  
							    }else{
							    	String responseStr=response_time.split(":")[0];
							    	int responseNum = Integer.parseInt(responseStr);
							    	int day=responseNum/24;
							    	int hour=responseNum%24;
							    	String hourStr=hour+"";
							    	if(hour<10){
							    		hourStr="0"+hour;
									}
							    	textValue=day+"天"+hourStr+":"+response_time.split(":")[1]+":"+response_time.split(":")[2];
							    }
									
							}else{
								textValue = dataMap.get(columns[i]);
							}
						}catch(Exception e){
							e.printStackTrace();
						}
						if (textValue instanceof Date) {
							Date date = (Date) textValue;
							SimpleDateFormat sdf = new SimpleDateFormat(pattern);
							textValue = sdf.format(date);
						} else if (textValue instanceof byte[]) {
							sheet.setColumnWidth(i, 35 * 100);
							XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 1023, 255, 6, index, 6, index);
							anchor.setAnchorType(2);
						} else {
							// 其它数据类型都当作字符串简单处理
							if(textValue!=null){
								textValue = textValue+"";
							}
							
						}

						if (textValue != null) {
							Pattern p = Pattern.compile("^//d+(//.//d+)?$");
							Matcher matcher = p.matcher(textValue+"");
							if (matcher.matches()) {
								// 是数字当作double处理
								cell.setCellValue(Double.parseDouble(textValue+""));
							} else {
								XSSFRichTextString richString = new XSSFRichTextString(textValue+"");
								cell.setCellValue(richString);
							}
						}

					}
				}
			}
			return workbook;
		}	
}